package cn.wolfcode.shop.cloud.filter;


import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.feign.UserInfoFeignApi;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieRefreshFilter extends ZuulFilter {

    @Autowired
    private UserInfoFeignApi userInfoFeignApi;


    /**
     * filter的类型
     */
    @Override

    public String filterType() {

        return FilterConstants.POST_TYPE;

    }

    /**
     * 定义优先级
     *
     * @return
     */
    @Override
    public int filterOrder() {

        return 0;

    }

    /**
     * 判断哪些是要进行过滤的,进入run方法过滤,判断什么时候需要延长时间
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //判断请求中是否携带着cookie  name=userToken
        //要拿到请求中的cookie
        RequestContext context = RequestContext.getCurrentContext();

        HttpServletRequest request = context.getRequest();

        String token = CookieUtil.getCookieValue(request, "userToken");

        if (!StringUtils.isEmpty(token)) {

            return true;

        }
        return false;

    }

    @Override
    //延长用户在redis中的存储时间
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = CookieUtil.getCookieValue(request, "userToken");
        //获取响应对象
        HttpServletResponse response = context.getResponse();

        //延迟redis过期时间,在会员服务中操作
        //远程调用会员服务
        Result<Boolean> result = userInfoFeignApi.refreshRedidToken(token);

        if (result != null && result.getCode() == 200 && result.getData()) {
            //延长cookie的过期时间

            CookieUtil.addCookie("userToken", token, 1800, response);
        }
        //shouldFilter没有过,其他就不用走了
        context.setSendZuulResponse(false);
        return null;

    }

}